<template>
  <div v-loading="allLoading">
    <div>
      <i class="el-icon-document">{{ listName }}</i>
    </div>
    <div class="panel-border">
      <el-row>
        <el-col v-if="modelType=='add'" :span="24">
          <el-form ref="form" :model="form" :rules="rules" label-width="130px" size="mini" inline label-position="center">
            <el-col :span="24">
              <el-form-item :label="$t('rosterList.listTable.specialListName') + ':'" prop="specialListName" size="mini">
                <el-input
                  v-model="form.specialListName"
                  maxlength="200"
                  type="text"
                  :disabled="modelTypes=='add' ? false :true "
                  :placeholder="$t('rosterList.placeholder.specialListName')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item style="border: none" :label="$t('rosterList.importType') + ':'" size="mini">
                <el-radio v-model="form.radioImport" style="border: none;" :label="1" border :disabled="modelTypes=='add' ? true : false" size="mini">{{ addSpecialListName }}</el-radio>
                <el-radio v-if="modelTypes!='add'" v-model="form.radioImport" style="border: none;" :label="2" border size="mini">{{ deleteSpecialListName }}</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item style="border: none" :label="$t('rosterList.templateDownload') + ':'" size="mini">
                <div style="width:130px;height:28px;border: none;">
                  <i class="el-icon-document">
                    <el-link
                      :href="'/taglib-web'+'/templates/Roster Template.xlsx'"
                      type="text"
                      v-text="'xslx template'"
                    />
                  </i>
                  <!--                                    <i class="el-icon-document" @click="downTemplateFiles">xslx template</i>-->
                </div>
              </el-form-item>
            </el-col>
          </el-form>
          <el-form
            ref="formImport"
            :model="formData"
            label-width="130px"
            size="mini"
            inline
            label-position="center"
          >
            <el-col :span="24">
              <el-form-item style="border: none;height: 60px" :label="$t('rosterList.import') + ':'" size="mini" required>
                <el-upload
                  ref="upload"
                  class="upload-demo"
                  :action="uploadAddr"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :file-list="fileList"
                  :limit="1"
                  :data="formData"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :auto-upload="false"
                  :on-change="checkFile"
                  :before-upload="beforeUpload"
                  :accept="accept"
                >
                  <el-button slot="trigger" size="small" type="primary">{{ chooseFile }}</el-button>
                  <el-button
                    style="margin-left: 10px;"
                    size="small"
                    type="success"
                    @click="submitUpload"
                    v-text="$t('modelMining.upload')"
                  />
                </el-upload>
              </el-form-item>
            </el-col>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <div style="padding-top: 26px;">
      <i class="el-icon-date">{{ listName }}</i>
    </div>
    <div class="panel-border">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane :label="$t('rosterList.all')+'('+importCount.alls+')'" name="all" />
        <el-tab-pane :label="$t('rosterList.success')+'('+importCount.success+')'" name="success" />
        <el-tab-pane :label="$t('rosterList.fail')+'('+importCount.fail+')'" name="fail" />
      </el-tabs>
      <avue-crud
        ref="crudList"
        :option="option"
        :data="optionData"
        :page.sync="page"
        :table-loading="loading"
        @on-load="initData"
        @refresh-change="refreshChange"
      >
        <template slot="statusCd" slot-scope="scope">
          <span
            v-for="item in statusCd"
            v-if="item.item_code == scope.row.statusCd"
            :label="item.item_code"
          >{{ item.item_text }}</span>
        </template>
        <template slot="objType" slot-scope="scope">
          <span
            v-for="item in objTypes"
            v-if="item.item_code == scope.row.objType"
            :label="item.item_code"
          >{{ item.item_text }}</span>
        </template>
        <template slot="menuRight">
          <el-button type="primary" icon="el-icon-edit" size="small" @click="errorExport" v-text="$t('rosterList.errorExport')" />
        </template>
        <template slot="empty">
          <avue-empty
            image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
            :desc="$t('empty')"
          >
            <br>
          </avue-empty>
        </template>
      </avue-crud>
    </div>
    <div class="panel-border">
      <p>{{ importExplain }}</p>
      <p style="margin-left: 20px;">{{ importExplain1 }}</p>
      <p style="margin-left: 20px;">{{ importExplain2 }}</p>
      <p style="margin-left: 20px;">{{ importExplain3 }}</p>
    </div>
    <div class="dialog-footer" style="text-align: center;">
      <el-button @click="onCloseImport" v-text="$t('close')" />
      <el-button type="primary" @click="onSubmit" v-text="$t('submit')" />
    </div>

  </div>
</template>

<script>
import { selectComTagDataList } from '@/utils/util'
import { taglibUrl } from '../../config/env'
import { getTagTicket } from '../../utils/auth'
export default {
  name: 'MktSpecialListDetailList',
  components: {

  },
  props: {
    modelTypes: {
      type: String,
      default: ''
    },
    rosterStatusCd: {
      type: Array,
      default: []
    },
    rosterNameOne: {
      type: String,
      default: ''
    },
    paramSpecialListId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      allLoading: false,
      loading: false,
      importFlag: false,
      activeName: 'all',
      checkFileFlag: false,
      chooseFile: this.$t('rosterList.chooseFile'),
      importExplain: this.$t('rosterList.importExplain'),
      importExplain1: this.$t('rosterList.importExplain1'),
      importExplain2: this.$t('rosterList.importExplain2'),
      importExplain3: this.$t('rosterList.importExplain3'),
      addSpecialListName: this.$t('rosterList.addSpecialListName'),
      deleteSpecialListName: this.$t('rosterList.deleteSpecialListName'),
      radioImport: 1,
      listName: this.$t('rosterList.listName'),
      rosterStatusCds: [],
      statusCd: [],
      objTypes: [],
      accept: '.xlsx',
      uploadAddr: taglibUrl + '/mktSpecialList/importFile',
      formData: {
        param: 1
      },
      searchData: {
        statusCd: '',
        importBatchId: -1
      },
      rules: {
        specialListName: [
          { required: true, message: this.$t('rosterList.rules.specialListName'), trigger: 'blur' },
          { min: 1, max: 200, message: this.$t('rosterList.rules.specialListNameLength'), trigger: 'blur' }
        ]
      },
      defaultValue: {
        specialListName: '',
        specialListDesc: '',
        statusCd: '1200'
      },
      form: {
        specialListName: this.rosterNameOne,
        specialListDesc: '',
        statusCd: '1200',
        radioImport: 1,
        specialListId: this.paramSpecialListId,
        importBatchId: -1
      },
      fileList: [],
      specialListId: 0,
      modelType: 'add',
      highLight: true,
      optionData: [
      ],
      importCount: {
        success: 0,
        alls: 0,
        fail: 0
      },
      option: {
        index: true,
        indexLabel: this.$t('serialNumber'),
        indexWidth: 120,
        border: true,
        page: false,
        menu: false,
        align: 'center',
        menuAlign: 'center',
        stripe: true,
        column: [
          // {
          // 	label: '序号',
          // 	prop: 'labelId',
          // },
          {
            label: '名单对象类型',
            prop: 'objType',
            slot: true,
            overHidden: true,
            minWidth: 50
          }, {
            label: '名单对象号码',
            prop: 'objId',
            overHidden: true,
            minWidth: 50
          }, {
            label: '用户名称',
            prop: 'objName',
            overHidden: true,
            minWidth: 50
          }, {
            label: '导入状态',
            prop: 'statusCd',
            slot: true,
            overHidden: true,
            minWidth: 50
          }, {
            label: '解析失败原因',
            prop: 'errorReason',
            overHidden: true,
            minWidth: 200
          }
          // ,{
          //     label: '创建员工',
          //     prop: 'staffName',
          //     overHidden:true,
          //     minWidth: 50,
          // },{
          //     label: '创建时间',
          //     prop: 'createDate',
          //     type:'date',
          //     format:'yyyy-MM-dd HH:mm:ss',
          //     overHidden:true,
          //     minWidth: 50,
          // }
          // ,{
          //     label: '操作',
          //     prop: 'option',
          //     slot: true,
          //     overHidden:true,
          //     minWidth: 100,
          // }
        ],
        saveBtn: false,
        updateBtn: false,
        cancelBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false
      },
      options: [],
      params: {},
      page: {
        total: 0,
        limit: 10,
        pageSize: 10,
        pagerCount: 5
      },
      pageInit: {
        total: 0,
        limit: 10,
        pageSize: 10,
        pagerCount: 5
      },
      tagData: [],
      reqParams: {}

    }
  },
  watch: {
    '$i18n.locale': {
      handler() {
        this.U.changeTableLanguage(this, this.option.column, 'rosterList.listDetailTable.')
      },
      immediate: true
    }
  },
  created() {

  },
  methods: {
    initData() {
      this.getSearchObject()
      this.params = this.searchData
      this.getLabelDataImport()
    },
    getSearchObject() {
      this.R.forTaglib.getDict('MKT_DATA_IMPORT_TMP_STATUS_CD').then((res) => {
        this.importStatusCds = res
        this.statusCd = res
      })
      this.R.forTaglib.getDict('MKT_SPECIAL_LIST_DETAIL_OBJ_TYPE').then((res) => {
        this.objTypes = res
      })
    },
    editStatus(specialListId, status) {
      var confLog = ''
      if (status == 1000) {
        confLog = this.$t('rosterList.tip.enAble')
      } else if (status == 1200) {
        confLog = this.$t('rosterList.tip.shutDown')
      }
      this.$confirm(confLog, this.$t('tip'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(() => {
        const that = this
        that.loading = true
        this.reqParams.specialListId = specialListId
        this.reqParams.statusCd = status
        this.R.forTaglib.postJson('/mktSpecialList/update', this.reqParams).then(res => {
          if (res.ok) {
            this.$message.success(this.$t('operateSuccess'))
            this.getLabelData()
          }
        }).catch(err => {
          that.$message.error(err.toString())
        })
        that.loading = false
      })
    },
    // 搜索
    onSearch() {
      console.log('列表事件onSearch')
      this.params = this.searchData
      this.getLabelDataImport()
    },
    onReset() {
      console.log('重置事件onSearch')
      this.searchData.specialListName = ''
      this.searchData.statusCd = ''
      this.getLabelDataImport()
    },
    getLabelDataImport() {
      const that = this
      that.loading = true
      this.page.limit = this.page.pageSize
      this.page.offset = this.page.currentPage
      const reqParam = this.R.extend(this.params, this.page)
      this.R.forTaglib.postJson('/mktSpecialList/queryImportList', reqParam).then(res => {
        that.page.total = res.rowCount
        this.page.currentPage = res.offset
        this.importCount = res.importCount
        that.optionData = res.dataList
        that.loading = false
      }).catch(err => {
        that.$message.error(err.toString())
      })
    },
    refreshChange() {
      this.getLabelDataImport()
    },
    onSubmit() {
      this.$refs.formImport.validate(valid => {
        if (valid) {
          this.allLoading = true
          if (this.importFlag) {
            this.R.forTaglib.postJson('/mktSpecialList/addByNumber', this.form).then(res => {
              if (res.ok) {
                this.$message.success(this.$t('saveSuccess'))
                this.allLoading = false
                this.$emit('onAddSuccess', true)
              } else {
                this.allLoading = false
              }
            }).catch(err => {
              this.allLoading = false
              this.$message.error(err.toString())
            })
          } else {
            this.$message.error(this.$t('rosterList.noImportTip'))
          }
        }
      })
    },
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (testmsg != 'xlsx') {
        this.$message({
          message: this.$t('rosterList.noXlxsFileTip'),
          type: 'warning'
        })
        return false
      }
      if (file.size > 10485760) {
        this.$message({
          message: this.$t('rosterList.noMore10M'),
          type: 'warning'
        })
        return false
      }
    },
    checkFile(file, fileList) {
      if (fileList.length > 0) {
        var flag = false
        fileList.forEach(function(item) {
          if (item.status == 'ready') {
            flag = true
          }
        })
        if (flag) {
          this.checkFileFlag = true
        } else {
          this.checkFileFlag = false
        }
      } else {
        this.checkFileFlag = false
      }
    },
    submitUpload() {
      if (this.checkFileFlag) {
        this.allLoading = true
        this.$refs.upload.submit()
      } else {
        this.$message.success(this.$t('rosterList.pleaseChooseFile'))
      }
    },
    handleRemove(file, fileList) {
      // return this.$confirm(`make sure you remove ${file.name}?`);
    },
    handlePreview(file) {
      console.log(file)
    },
    handleClick(tab, event) {
      if (tab.name == 'success') {
        this.searchData.statusCd = '1000'
      } else if (tab.name == 'fail') {
        this.searchData.statusCd = '1400'
      } else {
        this.searchData.statusCd = ''
      }
      this.onSearch()
    },
    handleSuccess(importBatchId) {
      this.allLoading = false
      this.searchData.importBatchId = importBatchId
      this.form.importBatchId = importBatchId
      this.$message.success(this.$t('uploadSuccess'))
      this.importFlag = true
      this.onSearch()
    },
    handleError(err, file, fileList) {
      this.allLoading = false
      this.$message.error(`${file.name} upload fail`)
    },
    onCloseImport() {
      // var confLog = "";
      if (this.importFlag) {
        this.$confirm(this.$t('rosterList.cancleTips'), this.$t('tip'), {
          confirmButtonText: this.$t('submitText'),
          cancelButtonText: this.$t('cancelText'),
          type: 'warning'
        }).then(() => {
          const that = this
          that.loading = true
          this.R.forTaglib.postJson('/mktSpecialList/updateMktDataImportTmp', { importBatchId: this.searchData.importBatchId }).then(res => {
            if (res.ok) {
              this.$message.success(this.$t('operateSuccess'))
              this.$emit('onAddSuccess', true)
              that.loading = false
            }
          }).catch(err => {
            that.loading = false
            that.$message.error(err.toString())
          })
        })
      } else {
        this.$emit('onAddSuccess', true)
      }
    },
    errorExport() {
      if (this.importCount.fail > 0) {
        window.location.href = taglibUrl + '/mktSpecialList/downloadImportFailedFile?importBatchId=' + this.form.importBatchId
      } else {
        this.$message.error(this.$t('rosterList.noErrorDataTip'))
      }
    },
    downTemplateFiles() {
      window.location.href = taglibUrl + '/mktSpecialList/downloadTemplateFile'
    }
  }
}
</script>

<style>

</style>

